package com.example.xm.config;

import com.example.xm.exception.SerceiceException;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class ChatWebSocketHandler extends TextWebSocketHandler {
    private static final HashMap<String, WebSocketSession> userSessions = new HashMap<>();

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        // 处理客户端发送的消息
        System.out.println("接收到消息：" + message.getPayload());
        String payload = message.getPayload();
        // 向客户端发送消息
        try {
            System.out.println("---------");
            for (String s : userSessions.keySet()) {
                System.out.println(s);
            }
            System.out.println("++++++++===");
            String[] split = payload.split("::", 3);
            String userid = split[0];
            String sendid = split[1];
            String content = split[2];
            WebSocketSession webSocketSession = userSessions.get(sendid);
            if (webSocketSession != null) {
                try {
                    webSocketSession.sendMessage(new TextMessage(userid+"::"+content));
                    System.out.println(userid+"发送消息给用户 " + sendid + ": " + content);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String userId = session.getUri().getQuery();  // 获取查询字符串
        userSessions.put(userId.split("=")[1],session);
        System.out.println("WebSocket 连接成功，用户ID: " + userId.split("=")[1]);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String userId = session.getUri().getQuery();
        userSessions.remove(userId);
        System.out.println("连接已关闭，客户端ID：" + userId);
    }
}
